package com.spica.platform.base.filter.user;

import com.spica.platform.base.context.SysUserContextHolder;
import com.spica.platform.base.filter.FilterCondition;
import com.spica.platform.base.model.SysUser;
import com.spica.platform.base.utils.UserUtil;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Conditional;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 获取当前登录人过滤器
 */
@ConditionalOnClass(Filter.class)
@Conditional(FilterCondition.class)
public class LoginUserFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
                                    FilterChain filterChain) throws IOException, ServletException {
        try {
            SysUser user = UserUtil.getCurrentUser(request, false);
            
            SysUserContextHolder.setUser(user);
            filterChain.doFilter(request, response);
        } finally {
        	SysUserContextHolder.clear();
        }
    }
}
